<template>
  <edit-card :title="title" :confirm-text="'创建'" :type="taskId ? 'edit' : 'add'" :loading="loading" @confirm="confirmTask">
    <div class="edit-task">
      <a-form
        ref="taskFormRef"
        :model="formState"
        :rules="taskRules"
        :label-col="{ style: { width: '120px' } }"
        class="w-560"
        label-align="left"
      >
        <a-form-item label="任务名称" name="name">
          <div class="w-440">
            <a-input v-model:value="formState.name" v-trim placeholder="请输入任务名称" :disabled="!!taskId" :maxlength="200" />
          </div>
        </a-form-item>
        <div class="tag-select">
          <div class="left">
            <a-form-item label="清洗类型" name="type">
              <a-radio-group v-model:value="formState.type" :disabled="!!taskId" :options="typeOptions" />
            </a-form-item>
          </div>
        </div>
        <a-form-item label="清洗数据集" name="dataIds">
          <div class="w-866">
            <g-select-tree-data
              ref="selectDataBucketRef"
              v-model:checked-ids="formState.dataIds"
              type-name="数据集"
              :disabled="!!taskId"
              :get-tree-data-api="selectTreeDataApi.dataBucketTree"
              :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
              :get-list-data-api="selectTreeDataApi.searchBucketList"
              :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
              :field-names="{ children: 'children', title: 'name', key: 'id' }"
              @change="changeData"
            />
          </div>
        </a-form-item>
        <a-form-item label="清洗方式" name="scheme">
          <a-checkbox-group v-model:value="formState.scheme">
            <div class="scheme-wrap w-704">
              <div>
                <a-checkbox class="mb-16 mt-8" :value="1">去近似</a-checkbox>
                <div class="option-wrap">
                  <div class="option-input-wrap" style="display: block">
                    <!-- :no-style="!formState.scheme.includes(1)" -->
                    <a-form-item name="similarity" :rules="[{ required: formState.scheme.includes(1), message: '请选择匹配模式' }]">
                      <span class="w-126 mr-24">匹配模式</span>
                      <a-radio-group
                        v-model:value="formState.similarity"
                        :disabled="!formState.scheme.includes(1)"
                        :options="radioOptions"
                      />
                    </a-form-item>
                  </div>
                  <a-checkbox-group
                    v-model:value="formState.approximate"
                    :disabled="!formState.scheme.includes(1)"
                    name="option-checkbox-group"
                    class="mt-8"
                  >
                    <div class="w-100%">
                      <a-checkbox class="w-50%" value="rotated">查找旋转过的</a-checkbox>
                      <a-checkbox class="w-50%" value="retroFleeted">查找翻转过的</a-checkbox>
                    </div>
                    <div class="w-100% mt-30">
                      <a-checkbox class="w-50%" value="sameSize">相同尺寸</a-checkbox>
                      <a-checkbox class="w-50%" value="sameAspectRatio">相同长宽比</a-checkbox>
                    </div>
                  </a-checkbox-group>
                </div>
              </div>
              <div>
                <a-checkbox class="mb-16 mt-8" :value="2">去模糊</a-checkbox>
                <div class="option-wrap">
                  <div class="option-input-wrap">
                    <p class="w-126">清晰度大于等于</p>
                    <a-form-item
                      name="definition"
                      :no-style="!formState.scheme.includes(2)"
                      :rules="[{ required: formState.scheme.includes(2), message: '请填写清晰度' }]"
                    >
                      <a-input-number
                        v-model:value="formState.definition"
                        :disabled="!formState.scheme.includes(2)"
                        :min="0"
                        :max="100"
                        :precision="0"
                        step="1"
                        class="w-104"
                      />
                    </a-form-item>
                  </div>
                </div>
              </div>
            </div>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import GSelectTreeData from '@/components/GSelectTreeData/index.vue'
  import { dataCleaningApi, selectTreeDataApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  import { radioOptions, taskTypeArr } from '../options'

  interface form {
    dataIds: string[]
    description?: string
    name: string
    type: number
    similarity: string
    definition: number
    // config: any
    [key: string]: any
  }

  const route = useRoute()
  const router = useRouter()

  const taskFormRef = ref()

  const taskId = route.params.id as string | ''
  const formState = ref<form>({
    name: '',
    approximate: [],
    dataIds: [],
    type: 1,
    similarity: 'medium',
    definition: 60,
    scheme: []
  })
  const title = computed(() => {
    return taskId ? `编辑任务（${formState.value.name}）` : '创建任务'
  })
  let validateAckData = async (rule: Rule, value: string) => {
    if (value.length === 0) {
      return Promise.reject('请选择数据集')
    }

    return Promise.resolve()
  }
  const taskRules: Record<string, Rule[]> = {
    name: [
      { required: true, trigger: 'change', message: '请输入任务名称' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    dataIds: [{ required: true, trigger: 'change', validator: validateAckData }],
    type: [{ required: true, trigger: 'change', message: '请选择方式' }],
    scheme: [{ required: true, trigger: 'change', message: '请选择清洗方式' }]
  }
  // 类型组
  const typeOptions = ref(taskTypeArr)

  // TODO: 数据集数据
  const selectDataBucketRef = ref<InstanceType<typeof GSelectTreeData>>()

  // TODO:确定
  const confirmTask = () => {
    taskFormRef.value
      .validate()
      .then(() => {
        submitForm()
      })
      .catch((err: any) => {
        console.log(err)
      })
  }

  const { loading, runAsync: runAddDataCleaning } = useRequest(dataCleaningApi.add)

  const submitForm = async () => {
    const approximate = {
      similarity: formState.value.scheme.includes(1) ? formState.value.similarity : '',
      rotated: formState.value.approximate.includes('rotated'),
      sameSize: formState.value.approximate.includes('sameSize'),
      retroFleeted: formState.value.approximate.includes('retroFleeted'),
      sameAspectRatio: formState.value.approximate.includes('sameAspectRatio')
    }
    const definition = {
      definition: formState.value.scheme.includes(2) ? formState.value.definition : -1
    }
    const config = {
      approximate: approximate,
      definition: definition
    }
    const scheme = formState.value.scheme.length === 1 ? formState.value.scheme[0] : 4
    const params = {
      ...formState.value,
      scheme,
      config
    }
    try {
      await runAddDataCleaning(params, { isAddUid: true })

      message.success('操作成功')
      router.back()
    } catch (error) {
      console.log(error)
    }
  }

  const changeData = (data: any) => {
    formState.value.dataIds = data
  }
</script>

<style lang="less" scoped>
  .edit-task {
    :deep(.ant-form-item) {
      margin-bottom: 40px;
    }

    :deep(.ant-form-item-label > label::after) {
      display: none;
    }

    :deep(.ant-radio-wrapper) {
      margin-right: 24px;
    }

    .ant-radio-wrapper :deep(.ant-transfer-list) {
      position: relative;

      .ant-transfer-list-header {
        height: 39px;
        background: #fafafa;
      }

      &:first-child {
        .ant-transfer-list-header {
          &::after {
            content: '待选';
            position: absolute;
            right: 8px;
          }
        }
      }

      &:last-child {
        .ant-transfer-list-header {
          &::after {
            content: '已选';
            position: absolute;
            right: 8px;
          }
        }
      }

      .ant-input-affix-wrapper {
        height: 32px;
        min-height: 32px !important;
      }
    }

    .tag-select {
      display: flex;

      .left {
        margin-right: 80px;
      }
    }
  }

  .scheme-wrap {
    display: flex;
    justify-content: space-between;
    gap: 0 40px;

    > div {
      width: 50%;
      border-radius: 2px;

      .option-wrap {
        display: flex;
        padding: 20px 24px;
        background: #fafafa;
        border-radius: 6px;
        flex-direction: column;
        gap: 24px 0;

        .option-input-wrap {
          display: flex;
          // align-items: center;
          font-size: 14px;
          color: rgba(25, 25, 48, 0.75);
          gap: 0 16px;
          font-weight: 400;
          line-height: 22px;

          > p {
            line-height: 32px;
          }

          :deep(.ant-form-item) {
            margin-bottom: 0;
          }
        }
      }
    }
  }
</style>
